package gui;

import framework.Color;
import framework.GameContext;
import framework.ImageTinter;
import framework.ImageWrapper;
import framework.KInput;
import framework.Screen;
import gamebackend.GameSession;

public class TouchToFlyOverlay extends Screen {

	/**
	 * How much the current frames vertical movement affects
	 * the total (0 < x < 1)
	 */
	private static final double ALPHA = .7;
	
	
	
	private GameSession my_gameSession;
	
	
	private boolean my_touchDown;
	private int my_lastX;
	private int my_lastY;
	private boolean my_special;
	
	/**
	 * A filtered total of vertical movement, used for detecting
	 * upward flings.
	 */
	private double my_verticalMovement;
	
	public TouchToFlyOverlay(final GameContext the_game, GameSession the_session) {
		super(the_game);
		my_gameSession = the_session;
	}

	@Override
	public void render() {
		my_gameSession.render();
	}

	@Override
	public void step(final int the_deltaTime) {
		final KInput input = my_game.getInput();
		input.getTouchEvents();
		final boolean touchDown = input.isTouchDown(0);
		if (touchDown) {
			if (!my_touchDown) {
				my_touchDown = true;
				my_lastX = input.getTouchX(0);
				my_lastY = input.getTouchY(0);
				my_verticalMovement = 0;
			}
			my_gameSession.setTarget(input.getTouchX(0));
			if (my_special) {
				 if (my_lastY < input.getTouchY(0)) {
//					 my_special = false;
//					 my_gameSession.setControlState(GameSession.KEY_SPECIAL, false);
				 }
			} else {
				my_verticalMovement = (1-ALPHA) * my_verticalMovement +
						ALPHA * the_deltaTime * (my_lastY - input.getTouchY(0));// / (1 + Math.abs(input.getTouchX(0) - my_lastX) / 8);
				if (my_verticalMovement > my_game.getGraphicsWrapper().getHeight() * .8) {
					my_verticalMovement = 0;
					my_gameSession.setControlState(GameSession.KEY_SPECIAL, true);
					my_special = true;
				}
				if (my_verticalMovement < 0) {
					my_verticalMovement = 0;
				}
			}
			my_lastX = input.getTouchX(0);
			my_lastY = input.getTouchY(0);
		} else {
			if (my_touchDown) {
				my_touchDown = false;
				my_special = false;
				my_gameSession.setControlState(GameSession.KEY_SPECIAL, false);
				my_gameSession.onTouchUp();
			}
		}
		
		my_gameSession.step(the_deltaTime);
	}
	
	@Override
	public void dispose() {
		my_gameSession.dispose();
	}
	@Override
	public void keyPressed(final int the_key) {
		my_gameSession.keyPressed(the_key);
	}
	@Override
	public void keyReleased(final int the_key) {
		my_gameSession.keyReleased(the_key);
	}

}
